package com.northming.daytodo.util.mail.impl;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.northming.daytodo.exception.RuntimeServiceException;
import com.northming.daytodo.util.mail.MailConfig;
import com.northming.daytodo.util.mail.MailService;
import com.northming.daytodo.util.mail.Pair;

@Service
public class MailServiceImpl implements MailService {
	
	@Autowired  
	private MailConfig emailConfig;  
	@Autowired  
	private JavaMailSender mailSender;
	   

	@Override
	public void sendSimpleMail(String sendTo, String title, String content) {
		SimpleMailMessage message = new SimpleMailMessage();  
        message.setFrom(emailConfig.getEmailFrom());  
        message.setTo(sendTo);  
        message.setSubject(title);  
        message.setText(content); 
        mailSender.send(message); 

	}

	@Override
	public void sendAttachmentsMail(String sendTo, String title, String content, List<Pair<String, File>> attachments) {
		MimeMessage mimeMessage = mailSender.createMimeMessage();  
		  
        try {  
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);  
            helper.setFrom(emailConfig.getEmailFrom());  
            helper.setTo(sendTo);  
            helper.setSubject(title);  
            helper.setText(content);  
  
            for (Pair<String, File> pair : attachments) {  
                helper.addAttachment(pair.getLeft(), new FileSystemResource(pair.getRight()));  
            }  
        } catch (Exception e) {  
            throw new RuntimeServiceException(e);  
        }  
  
        mailSender.send(mimeMessage);  

	}

	@Override
	public void sendTemplateMail(String sendTo, String title, Map<String, Object> content,
			List<Pair<String, File>> attachments) {
		// TODO Auto-generated method stub

	}

}
